<template>
  <!-- 富文本组件（直接引用即可） -->
  <div class="my-wary">
    <div ref="editor"></div>
  </div>
</template>
<script>
import { qiniuUploadImg } from "@/utils";

import { reactive, ref, watchEffect, toRefs, onMounted, nextTick } from "vue";
import WangEditor from "wangeditor";
export default {
  props: {
    goodsDetails: String,
  },
  setup(props, context) {
    const editor = ref(null);
    const state = reactive({
      //属性
      content: "",
    });
    watchEffect(() => {
      state.content = props.goodsDetails;
    });
    onMounted(() => {
      nextTick(() => {
        //富文本
        richTxt();
      });
    });
    //富文本
    let instance;
    const richTxt = () => {
      instance = new WangEditor(editor.value);
      instance.config.showLinkImg = false;
      instance.config.showLinkImgAlt = false;
      instance.config.showLinkImgHref = false;
      instance.config.uploadImgMaxSize = 2 * 1024 * 1024; // 2M
      //上传并插入图片
      instance.config.customUploadImg = (resultFiles, insertImgFn) => {
        resultFiles.forEach((item) => {
          qiniuUploadImg({ file: item }, (files) => {
            let url = config.imgSrc.url + files.key;
            insertImgFn(url);
          });
        });
      };
      //富文本内容发生变化
      Object.assign(instance.config, {
        onchange() {
          context.emit("editorHtml", instance.txt.html()); //触发父组件
          //   console.log("*************change");
        },
      });
      instance.create();
      if (state.content != "") {
        if (instance) {
          // 初始化商品详情 html
          instance.txt.html(state.content);
        }
      }
    };
    return {
      ...toRefs(state),
      editor,
    };
  },
};
</script>
<style lang="scss" scoped>
.my-wary {
  position: relative;
  z-index: 1;
}
</style>